package com.hippo.javacore.multithreading;

/**
 * @ClassName ThreadDemo12
 * @Description TODO 死锁
 * @Author tangxl
 * @create 2023-03-14 15:13
 **/
public class ThreadDemo12 extends Thread {
    // 定义两个对象作为锁
    static Object obj1 = new Object();
    static Object obj2 = new Object();

    @Override
    public void run() {
        // 线程1先获取obj1锁，再获取obj2锁
        if (getName().equals("线程1")) {
            synchronized (obj1) {
                System.out.println("线程1获取到了obj1锁");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                synchronized (obj2) {
                    System.out.println("线程1获取到了obj2锁");
                }
            }
        }
        // 线程2先获取obj2锁，再获取obj1锁
        if (getName().equals("线程2")) {
            synchronized (obj2) {
                System.out.println("线程2获取到了obj2锁");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                synchronized (obj1) {
                    System.out.println("线程2获取到了obj1锁");
                }
            }
        }
    }

public static void main(String[] args) {
    /**
     * 需求：线程1获得了obj1锁，线程2获得了obj2锁，线程1想要获取obj2锁，线程2想要获取obj1锁，造成死锁
     */

    // 创建线程
        Thread t1 = new ThreadDemo12();
        Thread t2 = new ThreadDemo12();

        // 线程命名
        t1.setName("线程1");
        t2.setName("线程2");

        // 线程执行
        t1.start();
        t2.start();
    }
}
